//
//  SubjectMoreViewController.m
//  Wedding fantastic
//
//  Created by dllo on 15/7/2.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "SubjectMoreViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "RecommendModel.h"
#import "SubjectMoreCollectionCell.h"
#import "SubjectDetailVC.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface SubjectMoreViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
// 主题列表collectionView
@property (nonatomic, retain) UICollectionView *subjectCollectionView;
// 接收model的数组
@property (nonatomic, retain) NSMutableArray *modelArr;

@property (nonatomic, retain) MBProgressHUD *HUD;

@property (nonatomic, retain) NSMutableArray *refreshArr;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) BOOL loading;

@end

@implementation SubjectMoreViewController

- (void)dealloc
{
    [_subjectCollectionView release];
    [_modelArr release];
    [_HUD release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:241 / 255.0 green:241 / 255.0 blue:240 / 255.0 alpha:1];
    self.navigationItem.title = @"主题";
    // 设置标题颜色
    self.navigationController.navigationBar.tintColor = [UIColor brownColor];
    // 字体颜色
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor brownColor],NSForegroundColorAttributeName,nil]];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png" ] style:UIBarButtonItemStyleDone target:self action:@selector(leftBack:)];
    
    // 主题列表collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH / 2.5 * WIDTH / 375, 200 * HEIGHT / 667);
    flowLayout.sectionInset = UIEdgeInsetsMake(20 * WIDTH / 375, 25 * HEIGHT / 667, 5 * WIDTH / 375, 25 * HEIGHT / 667);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.subjectCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 560 * HEIGHT / 667) collectionViewLayout:flowLayout];
    self.subjectCollectionView.backgroundColor = [UIColor colorWithRed:223 / 255.0 green:223 / 255.0 blue:223 / 255.0 alpha:1];
    // collectionView和tableView很相似,使用前需要先签订两个协议,一个dataSource,一个delegate
    self.subjectCollectionView.delegate = self;
    self.subjectCollectionView.dataSource = self;
    [self.view addSubview:self.subjectCollectionView];
    [_subjectCollectionView release];
    
    // 注册
    // 第一个参数:需要指定注册类型
    // 第二个参数:重用的标志
    [self.subjectCollectionView registerClass:[SubjectMoreCollectionCell class] forCellWithReuseIdentifier:@"reuse"];
    
    // 回到顶部button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(300 * WIDTH / 375, 450 * HEIGHT / 667, 35 * WIDTH / 375, 38 * HEIGHT / 667);
    [button setBackgroundImage:[UIImage imageNamed:@"backTop"] forState:UIControlStateNormal];
    button.alpha = 0.6;
    [self.view addSubview:button];
    [button addTarget:self action:@selector(backTop:) forControlEvents:UIControlEventTouchUpInside];
    

    [self createData];
    self.page = 1;
    [self addHeader];
    [self addFooter];
}

// 回到顶部
- (void)backTop:(UIButton *)button
{
    [self.subjectCollectionView setContentOffset:CGPointZero animated:YES];
}

// 刷新
- (void)addHeader
{
    __block SubjectMoreViewController *subject = self;
    
    // 添加下拉刷新头部控件
    [self.subjectCollectionView addHeaderWithCallback:^{
        subject.loading = NO;//
        [self.subjectCollectionView reloadData];
        [self.subjectCollectionView headerEndRefreshing];
    }];
    
}

// 加载
- (void)addFooter
{
    __block SubjectMoreViewController *subject = self;
    //
    [self.subjectCollectionView addFooterWithCallback:^{
        subject.loading = NO;
        [subject footerRereshing];
    }];
}


// 上拉
- (void)footerRereshing
{
    self.page++;
    NSInteger maxPage = 4;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:[NSString stringWithFormat:@"http://hunliji.com/v1/api/app/newsubjects.json?page=%ld", (long)self.page] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dic = responseObject;
            NSArray *subjectsArr = dic[@"subjects"];
            for (NSDictionary *tempDic in subjectsArr) {
                RecommendModel *model = [[RecommendModel alloc] init];
                [model setValuesForKeysWithDictionary:tempDic];
                [self.modelArr addObject:model];
                [model release];
            }
            if (self.page == maxPage) {
                self.subjectCollectionView.footerHidden = YES;
            }
            [self.subjectCollectionView reloadData];
            [self.subjectCollectionView footerEndRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
    }


// 导航控制器返回按钮点击方法
- (void)leftBack:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}
// collectionView 方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.modelArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SubjectMoreCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    RecommendModel *model = self.modelArr[indexPath.row];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_path]];
    //3D效果
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];
    return cell;
}

//// 回到顶部
//- (void)backTop:(UIButton *)button
//{
//    [self.subjectCollectionView setContentOffset:CGPointZero animated:YES];
//}
//}
//
//
//// 刷新
//- (void)setupRefresh
//{
//    // 下拉刷新
//    [self.subjectCollectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
//    [self.subjectCollectionView headerBeginRefreshing];
//    
//    // 上拉加载
//    [self.subjectCollectionView addFooterWithTarget:self action:@selector(footerRereshing)];
//}
//// 下拉
//- (void)headerRereshing
//{
//    [self.subjectCollectionView reloadData];
//    // 刷新结束
//    [self.subjectCollectionView headerEndRefreshing];
//}
//// 上拉
//- (void)footerRereshing
//{
//    self.page++;
//    NSInteger maxPage = 4;
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//        [manager GET:[NSString stringWithFormat:@"http://hunliji.com/v1/api/app/newsubjects.json?page=%ld", (long)self.page] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            NSDictionary *dic = responseObject;
//            NSArray *subjectsArr = dic[@"subjects"];
//            for (NSDictionary *tempDic in subjectsArr) {
//                RecommendModel *model = [[RecommendModel alloc] init];
//                [model setValuesForKeysWithDictionary:tempDic];
//                [self.modelArr addObject:model];
//                [model release];
//            }
//            if (self.page == maxPage) {
//                self.subjectCollectionView.footerHidden = YES;
//            }
//            [self.subjectCollectionView reloadData];
//            [self.subjectCollectionView footerEndRefreshing];
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            
//        }];
//    }










- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SubjectDetailVC *subjectVC = [[SubjectDetailVC alloc] init];
    subjectVC.sendModel = self.modelArr[indexPath.row];
    [self.navigationController pushViewController:subjectVC animated:YES];
    [subjectVC release];
}

// 解析数据
- (void)createData
{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.HUD setDimBackground:YES];
    self.HUD.labelText = @"努力加载中...";
    [self.HUD show:YES];
    
    self.modelArr = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://hunliji.com/v1/api/app/newsubjects.json?page=1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *subjectsArr = dic[@"subjects"];
        for (NSDictionary *tempDic in subjectsArr) {
            RecommendModel *model = [[RecommendModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.modelArr addObject:model];
            [model release];
        }
        [self.HUD hide:YES];
        [self.subjectCollectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"可怜的~" message:@"你的网络有问题哦~~%>_<%" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
        [alert release];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
